from fastapi import FastAPI, HTTPException
from fastapi.exceptions import RequestValidationError
from fastapi.middleware.cors import CORSMiddleware
from starlette.middleware.sessions import SessionMiddleware
from app.config import settings
from app.core.Router import AllRouter
from app.core.Events import startup, stopping
from app.core.Exception import http_error_handler, http422_error_handler, unicorn_exception_handler, UnicornException
from app.core.Middleware import Middleware
from typing import cast, Callable

app = FastAPI(
    debug=settings.APP_DEBUG,
    description=settings.DESCRIPTION,
    version=settings.VERSION,
    title=settings.PROJECT_NAME
    )


# 事件监听
app.add_event_handler("startup", startup(app))
app.add_event_handler("shutdown", stopping(app))


# 异常错误处理
app.add_exception_handler(HTTPException, http_error_handler) # type: ignore
app.add_exception_handler(RequestValidationError, http422_error_handler) # type: ignore
app.add_exception_handler(UnicornException, unicorn_exception_handler) # type: ignore

# 路由
app.include_router(AllRouter)

# 中间件
app.add_middleware(cast(Callable, Middleware),)
# Session
app.add_middleware(
    cast(Callable, SessionMiddleware),
    secret_key=settings.SECRET_KEY,
    session_cookie=settings.SESSION_COOKIE,
    max_age=settings.SESSION_MAX_AGE,
)
# CSRF跨域
app.add_middleware(
    cast(Callable, CORSMiddleware),
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=settings.CORS_ALLOW_CREDENTIALS,
    allow_methods=settings.CORS_ALLOW_METHODS,
    allow_headers=settings.CORS_ALLOW_HEADERS,
)



